<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use think\facade\View;
use think\facade\Db;
use app\common\model\AdConf as A_M;
use app\common\model\FragmentInfo as F_M;
/**
 * 控制器基础类
 */
abstract class BaseController
{
    use \app\common\traits\Base;
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
		$this->app     = $app;
		$this->request = $this->app->request;
		define('GROUN_NAME',app('http')->getName());
		define('MODULE_NAME',$this->request->controller());
		define('ACTION_NAME',$this->request->action());
		
        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize(){
		
	}

    // 获取系统参数
    protected function getSystem(){
        return [
            'os' => PHP_OS,
			'app_name'=> config_cache_file('versions.app_name'),
			'author'=> config_cache_file('versions.author'),
            'space' => round((disk_free_space('.')/(1024*1024)),2).'M',
            'addr' =>$_SERVER['HTTP_HOST'],
            'run' => $this->request->server('SERVER_SOFTWARE'),
            'php' => PHP_VERSION,
            'php_run' => php_sapi_name(),
            'mysql' => function_exists('mysql_get_server_info')?mysql_get_server_info():\think\facade\Db::query('SELECT VERSION() as mysql_version')[0]['mysql_version'],
            'think' => $this->app->version(),
            'upload' => ini_get('upload_max_filesize'),
            'max' => ini_get('max_execution_time').'秒',
            'ver' => config_cache_file('versions.ver'),
        ];
    }

    protected function getJson($json = [],$replace=false){
		if(is_numeric($json)){
            if(!$replace){
                $code=$json;
                $msg=config_cache_file('codemsg.'.$code);
                $json=[
                	'code'=>$code,
                	'msg'=>$msg,
                ];
            }
		}

        if('json' == strtolower($this->getResponseType())){
            return $this->json($json['msg']??'操作成功',$json['code']??200,$json['data']??[],$json['extend']??[]);
        }else{
			return $this->request->isAjax()? $this->json('您请求的页面不存在哦！',404):$this->error('您请求的页面不存在哦！');
		}
    }

    //页面分配变量
    protected function assign($key,$value)
    {
        return View::assign($key,$value);
    }

    //页面渲染 
    protected function fetch($template = '',$data = [])
    {
        return View::fetch($template,$data);
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }
	
	//获取相近颜色的数据
	public function analogyColor($hex,$inter=10,$where='',$limit=0){
		$data=array();
		$rgb=hex2rgba($hex);
		if(count($rgb)>2){
			$red1=$rgb[0]-$inter;
			$red2=$rgb[0]+$inter;
			$green1=$rgb[1]-$inter;
			$green2=$rgb[1]+$inter;
			$blue1=$rgb[2]-$inter;
			$blue2=$rgb[2]+$inter;
			$sql='select a.*,b.square,b.breadth,b.title,(abs(a.red-'.$rgb[0].')+abs(a.green-'.$rgb[1].')+abs(a.blue-'.$rgb[2].')) as near from '.env('database.prefix').'cloth_color as a left join '.env('database.prefix').'cloth_main as b on a.pid=b.id where b.status=1 and b.wx_isshow=1 and a.red>'.$red1.' and a.red<'.$red2.' and a.green>'.$green1.' and a.green<'.$green2.' and a.blue>'.$blue1.' and a.blue<'.$blue2;
			if($where!=''){
				$sql.=' and '.$where;
			}
			$sql.=' order by near asc';
			if($limit>0){
				$sql.=' limit 0,'.$limit;
			}
			$data=Db::query($sql);
		}
		return $data;
	}
	
	//获取当前模型广告配置文件
	public function getAdConf($name='',$uuid=0){
		$name=$name=='' ? GROUN_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME : $name;
		$name=strtolower($name);
		$AD=F($uuid.'/ad');
		if(is_null($AD)){
			$AD=$this->setAdCache($uuid);
		}
		$AD=$AD[$name];
		View::assign('AD',$AD);
		return $AD;
	}
	
	//缓存广告
	protected function setAdCache($uuid=0){
		$T=A_M::listData(['status'=>1,'uuid'=>$uuid],'sort asc');
		$data=[];
		foreach($T as $v){
			unset($v['sort']);unset($v['status']);unset($v['update_time']);
			$data[$v['model']][$v['mark']][]=$v;
		}		
		F($uuid.'/ad',$data);
		return $data;
	}
	
	//获取对应片段
	public function getFragment($parent,$uuid=0){
		$parent=strtolower($parent);
		$fragment=F($uuid.'/fragment');
		if($fragment==''){
			$PART=F_M::listData(['status'=>1,'uuid'=>$uuid]);
			$fragment=[];
			foreach($PART as $v){
				unset($v['uid']);unset($v['user']);unset($v['status']);unset($v['update_time']);
				$fragment[$v['p_mark']][$v['mark']][]=$v;
			}
			F($uuid.'/fragment',$fragment);
		}
		$fragment=$fragment[$parent];
		View::assign('PART',$fragment);
		return $fragment;
	}
}